import React from 'react';
import Editor from 'wangeditor'
import Block from 'fs-flex'
import {  List,InputItem,Button,Toast } from 'antd-mobile';
import { createForm } from 'rc-form';
import Canstant from '../../../../utils/constant'
import qs from 'qs'
import Header from '../../../../components/Header/index';


import CmsService from '../../../../services/CmsService'


class ContentEdit extends React.Component{
    state={
        id:null,
        title:null,
        textHtml:''
    }
    async componentDidMount() {
        const { id } = qs.parse(this.props.location.search.split('?')[1])
    
        var editor = new Editor(this.editPlugin);
        // 使用 onchange 函数监听内容的变化，并实时更新到 state 中
        editor.customConfig.uploadImgServer = Canstant.host+'upload/img'
        editor.customConfig.uploadFileName ='img'
        editor.customConfig.withCredentials = true
        editor.customConfig.onchange = (html) => {
          this.setState({
            editorHtml: html,
            editorText: editor.txt.text()
          })
          //将html值设为form表单的desc属性值
          this.props.form.setFieldsValue({
            'desc': html
          });
        }
        editor.customConfig.uploadImgHooks = {
            customInsert: function (insertImg, result, editor) {
                // console.log(insertImg)
                console.log(result)
                
                if(result.errno==='0'||result.errno===0){
                    var url = result.data[0]
                    console.log(Canstant.host+url)
                    insertImg(Canstant.host+url)
                }
                
                // result 必须是一个 JSON 格式字符串！！！否则报错
            }
        }
        editor.create();
        if(id){
            const {code,data}=await CmsService.detail(id)
            if (Canstant.responseOK === code) {
                this.setState({ 
                    id: id,
                    title:data.articleTitle,
                    textHtml:data.articleContent
                 })
                 editor.txt.html(data.articleContent)
            }
        }
    }

    //自定义表单验证规则
  validateEditorFrom = (rule, value, callback) => {
        //此处根据富文本框的text值进行验证，但注意富文本框中输入空格，使用‘&nbsp‘表示，此方法不能处理只输入空格的验证。
    if (this.state.editorText.trim() === '') {
        callback('不能为空');
    }
    // Note: 必须总是返回一个 callback，否则 validateFieldsAndScroll 无法响应
    callback();
}

save=async()=>{
    let data = this.props.form.getFieldsValue()
    if(!data.title){
        Toast.fail('请填写标题！',2)
        return
    }
    if(!data.desc || data.desc==='<p><br></p>'){
        Toast.fail('请填写内容！',2)
        return
    }
    const {code}=await CmsService.save({
        id:this.state.id?this.state.id:null,
        title:data.title,
        content:data.desc
    })
    if (code === Canstant.responseOK) {
        //路由
        this.props.history.push('/manage/cms/list')
    }
    
}

render(){
        const { getFieldProps,getFieldDecorator } = this.props.form;
        const titleStyle={
            fontSize: '17px',
            marginLeft: 0,
            marginRight: '5px',
            textAlign: 'left',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            padding: '2px 0',
            lineHeight: '1.4em'
        }
        return(
            <Block vf>
                <Block>
                    <Header needBack={true} history={this.props.history} title='操作说明编辑' />
                </Block>
                <List renderHeader='标题'>
                        <List.Item>
                        {getFieldDecorator('title', {
                        
                        initialValue: this.state.title
                        })(<InputItem clear placeholder="请输入标题"  ref={el => this.autoFocusInst = el}/>)}
                        </List.Item>
                    </List>
                    <List renderHeader='内容'>
                        <List.Item>
                        {getFieldDecorator('desc', {
                        rules: [{
                            required: true,
                            message: '请填写描述',
                        }, {// 使用自定义的校验规则
                            validator: this.validateEditorFrom
                        }],
                        initialValue: this.state.textHtml
                        })(<div ref={(ref) => this.editPlugin = ref}></div>)}
                        </List.Item>
                    </List>
                <Block a='c' j='c' h={60} fs={20}>
                    <Button type="primary" style={{width:'50%'}} onClick={this.save}>保存</Button>
                </Block>
            </Block>
        )
    }
}

export default createForm()(ContentEdit)